<template>
  <div class="read-page-wrapper">
    <van-nav-bar
      :title="chapterContent.name || 'Chapter'"
      class="variables-header-wrapper"
      left-arrow
      fixed
      @click-left="onClickLeft"
    />
    <div class="read-content-wrapper variables-wrapper">
      <div :style="fontSizeStyle" class="content-inner" :class="{ hidden: overlayVisible }" v-html="chapterContent.content">
      </div>
      <div class="status-wrapper" v-if="isEnd || isUpdating">
        <div v-if="isEnd">- END -</div>
        <div v-if="isUpdating">- Updating -</div>
      </div>
      <div class="content-pagination">
        <template v-if="mode === 'Night'">
          <van-button hairline type="default" :disabled="disabledPrev" @click="goToPrev">Prev</van-button>
          <van-button hairline type="default" :disabled="disabledNext" @click="goToNext">Next</van-button>
        </template>
        <template v-else>
          <van-button plain hairline type="success" :disabled="disabledPrev" @click="goToPrev">Prev</van-button>
          <van-button plain hairline type="success" :disabled="disabledNext" @click="goToNext">Next</van-button>
        </template>
      </div>
    </div>
    <div class="read-bottom-wrapper van-hairline--top">
      <div v-if="setFontVisible" class="font-wrapper">
        <div class="warn-text" :style="fontSizeStyle">Preview text.This setting will only affect the content.</div>
        <div class="btn-wrapper">
          <div class="btn btn-small" @click.stop="fontSizeDecrease">Small</div>
          <div class="btn btn-big" @click.stop="fontSizeIncrease">Big</div>
        </div>
      </div>
      <div class="read-menu-wrapper variables-navbar-wrapper van-hairline--top">
        <div class="read-menu-item" v-for="(tab, i) in tabs" :key="i" @click="tab.onClick">
          <van-icon :name="tab.icon" />
          <span class="menu-text">{{ tab.text }}</span>
        </div>
      </div>
    </div>

    <van-popup
      v-model="overlayVisible"
      :close-on-click-overlay="false"
      position="bottom"
      round
    >
      <Charge-Popup-Content
        :text="priceText"
        @yes="canPayReadClick"
        @no="notPayReadClick"
      />
    </van-popup>

  </div>
</template>

<script>
import { Popup } from 'vant'
import { mutations, state } from '@/custom-store/global.js'
import { getChapterDetail, trackingPagePv, trackingPayment } from '@/api/index'
import { getItem, setItem } from '@/utils/storage'
import ChargePopupContent from '@/components/charge-popup-content'
import { addReadItem } from '@/utils/read-record'

const FONT_SIZE_KEY = 'FONT_SIZE'

export default {
  components: {
    ChargePopupContent,
    [Popup.name]: Popup
  },

  computed: {
    chapterId() {
      return this.$route.query ? this.$route.query.id : ''
    },
    fontSizeStyle() {
      const fontSize = this.fontSize
      return {
        fontSize: fontSize + 'px'
      }
    },
    modeIndex() {
      return state.modeIndex
    },
    mode() {
      return state.mode
    },
    priceText() {
      return `As low as $${this.chapterContent.price} unlock and read the whole book ?`
    },
    disabledNext() {
      const next = this.chapterContent.next
      return !next || next === 'end' || next === 'updating'
    },
    isUpdating() {
      return this.chapterContent.next === 'updating'
    },
    isEnd() {
      return this.chapterContent.next === 'end'
    },
    disabledPrev() {
      return !this.chapterContent.prev
    },
    tabs() {
      return [
        { icon: 'setting-o', text: 'Chapters', onClick: this.gotoChapters },
        { icon: 'friends-o', text: 'More Storys', onClick: this.gotoDiscovery },
        { icon: 'setting-o', text: this.mode, onClick: this.setModeIndex },
        { icon: 'bag-o', text: 'Font', onClick: this.showSetFont }
        // { icon: 'info-o', text: 'Share', onClick: this.gotoChapters }
      ]
    }
  },

  created() {
    if (this.chapterId) {
      this.fetchChapterContent()
    }
  },

  data() {
    return {
      currentPage: 1,
      tabbar: '',
      setFontVisible: false,
      overlayVisible: false,
      fontSize: Number(getItem(FONT_SIZE_KEY)) || 14,
      chapterContent: {}
    }
  },

  methods: {
    uploadTrackingPv() {
      const { bookid, id } = this.chapterContent
      trackingPagePv({
        bookid,
        chapaterid: id
      }).then(res => {
        console.log('PV Tracking Done!')
        console.log(res)
      })
    },
    uploadTrackingPayment() {
      const { bookid, id, price } = this.chapterContent
      trackingPayment({
        bookid,
        chapaterid: id,
        price
      }).then(res => {
        console.log('Payment Tracking Done!')
        console.log(res)
      })
    },
    notPayReadClick() {
      this.overlayVisible = false
      this.$router.back()
    },
    canPayReadClick() {
      this.uploadTrackingPayment()
      this.overlayVisible = false
    },
    goToTargetChapter(id) {
      if (!id) {
        return console.log('Id is empty')
      }
      const query = { ...this.$route.query }
      query.id = id
      this.$router.replace({
        query
      })
      this.fetchChapterContent()
    },
    goToPrev() {
      const { prev } = this.chapterContent
      this.goToTargetChapter(prev)
    },
    goToNext() {
      const { next } = this.chapterContent
      this.goToTargetChapter(next)
    },
    fetchChapterContent() {
      getChapterDetail({
        id: this.chapterId
      }).then(res => {
        const { data } = res
        this.chapterContent = data || {}
        this.uploadTrackingPv()
        addReadItem({
          bookId: data.bookid,
          chapterId: data.id
        })
        this.overlayVisible = !!data.price
      })
    },
    updateFontSizeStore() {
      setItem(FONT_SIZE_KEY, this.fontSize)
    },
    fontSizeDecrease() {
      this.fontSize--
      this.updateFontSizeStore()
    },
    fontSizeIncrease() {
      this.fontSize++
      this.updateFontSizeStore()
    },
    setModeIndex() {
      mutations.setModeIndex((this.modeIndex + 1) % 3)
    },
    showSetFont(e) {
      this.setFontVisible = true
      const handleClick = () => {
        this.setFontVisible = false
        window.removeEventListener('click', handleClick)
      }
      window.addEventListener('click', handleClick)
      e.stopPropagation()
    },
    gotoChapters() {
      this.$router.push({
        name: 'Catalogue',
        query: {
          id: this.chapterContent.bookid,
          bookName: this.chapterContent.bookName
        }
      })
    },
    gotoDiscovery() {
      this.$router.push({
        name: 'Discovery'
      })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    onTabbarChange(name) {
      console.log(name)
      if (name === 'Chapters') {
        this.$router.push({
          name: 'Catalogue'
        })
      }
      if (name === 'MoreStorys') {
        this.$router.push({
          name: 'Discovery'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.read-content-wrapper {
  padding-top: 46px;
  padding-bottom: 50px;
  min-height: calc(100vh);
  box-sizing: border-box;
}

.content-inner {
  color: inherit;
  padding: 10px 15px;
  min-height: calc(100vh - 46px - 50px - 80px);
  font-size: 14px;
  line-height: 1.75;
  opacity: 1;

  &.hidden {
    opacity: 0;
  }
}

.content-pagination {
  display: flex;
  padding: 10px 15px;
  padding-bottom: 30px;
  button {
    flex: 1;
    margin-right: 20px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.read-bottom-wrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;

  .read-menu-wrapper {
    display: flex;
    padding: 6px 30px;
    justify-content: space-between;
  }

  .read-menu-item {
    font-size: 22px;
    // color: #646566;
    color: inherit;
    line-height: 1;
    text-align: center;
    cursor: pointer;

    .menu-text {
      font-size: 12px;
    }

    .van-icon {
      display: block;
      min-width: 1em;
    }
  }
}

.font-wrapper {
  padding: 10px 12px;
  .warn-text {
    font-size: 14px;
    font-weight: bold;
    padding-bottom: 10px;
  }

  .btn-wrapper {
    display: flex;
    border: 1px solid skyblue;
    border-radius: 10px;
    .btn {
      flex: 1;
      padding: 8px 0;
      text-align: center;
      color: skyblue;
      font-weight: bold;
      border-right: 1px solid skyblue;

      &:last-child {
        border-right: none;
      }
    }
  }
}

.status-wrapper {
  // padding: 10px 0;
  padding-bottom: 30px;
  text-align: center;
  font-size: 30px;
}
</style>
